﻿namespace Brjnk.Common.ValueTypes
{
    using System;
    using System.ComponentModel;

    /// Třída zajišťující konverzi mezi hodnotou (Azimuth, Distance, GpsCoordinates atd.) a její textovou reprezentací (obousměrně)
    /// </summary>
    /// <typeparam name="T">Typ hodnoty</typeparam>
    public class StringValueConverter<T> : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(string);
        }

        public override bool CanConvertTo(ITypeDescriptorContext context,
            Type destinationType)
        {
            return destinationType == typeof(string);
        }

        public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
        {
            return value.ToString();
        }

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
        {
            if (typeof(T) == typeof(Acceleration))
            {
                return (Acceleration)Acceleration.Parser.Parse((string)value);
            }
            else if (typeof(T) == typeof(Azimuth))
            {
                return (Azimuth)Azimuth.Parser.Parse((string)value);
            }
            else if (typeof(T) == typeof(Distance))
            {
                return (Distance)Distance.Parser.Parse((string)value);
            }
            else if (typeof(T) == typeof(GpsCoordinates))
            {
                GpsCoordinates retVal;
                bool success = GpsCoordinates.TryParse((string)value, out retVal);
                if (!success) throw new FormatException("Gps souřadnice nemají správný formát.");
                return retVal;
            }
            else if (typeof(T) == typeof(Speed))
            {
                return (Speed)Speed.Parser.Parse((string)value);
            }
            else
            {
                throw new Exception("Nepodporovaný typ ke konverzi.");
            }
        }
    }
}